package com.st.swagger.service;

import com.st.swagger.entity.Order;
import com.st.swagger.entity.Product;
import com.st.swagger.mapper.OrderMapper;
import com.st.swagger.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ProductMapper productMapper;

    /**
     * 获取所有订单
     */
    public List<Order> getAllOrders() {
        return orderMapper.findAll();
    }

    /**
     * 根据用户 ID 获取订单
     */
    public List<Order> getOrdersByUserId(Long userId) {
        return orderMapper.findByUserId(userId);
    }

    /**
     * 根据订单 ID 获取订单详情
     */
    public Order getOrderById(Long id) {
        return orderMapper.findById(id);
    }

    /**
     * 创建新订单
     */
    public Order createOrder(Order order) {
        // 检查商品是否存在
        Product product = productMapper.findById(order.getProductId());
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }

        // 检查库存是否充足
        if (product.getStock() < order.getQuantity()) {
            throw new RuntimeException("库存不足");
        }

        // 计算订单总价
        double totalPrice = product.getPrice() * order.getQuantity();
        order.setTotalPrice(totalPrice);
        order.setStatus("PENDING"); // 初始状态为待支付
        order.setOrderTime(LocalDateTime.now());

        // 插入订单
        orderMapper.insertOrder(order);

        // 更新商品库存
        product.setStock(product.getStock() - order.getQuantity());
        productMapper.updateProduct(product);

        return order;
    }

    /**
     * 更新订单状态
     */
    public void updateOrderStatus(Long id, String status) {
        Order order = orderMapper.findById(id);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        order.setStatus(status);
        orderMapper.updateOrder(order);
    }

    /**
     * 删除订单
     */
    public void deleteOrder(Long id) {
        if (orderMapper.findById(id) == null) {
            throw new RuntimeException("订单不存在");
        }
        orderMapper.deleteOrder(id);
    }
}

